package com.chagee.channel.api.bo;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.chagee.channel.api.bo.lark.ApprovalCommentListResponse;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

/**
 * @author: chang.jiawei
 * @date: 2024/01/24
 */
public class FastJsonSerializer {

    public static class EpochMillSerializer implements ObjectSerializer {

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
            if (Objects.isNull(object)) {
                return;
            }
            long ms = Long.parseLong(String.valueOf(object));
            if (NumberUtils.LONG_ZERO.equals(ms)) {
                serializer.writeNull();
                return;
            }
            LocalDateTime time = LocalDateTimeUtil.of(ms);
            serializer.write(time);
        }
    }


    public static class JsonArrayDeserializer implements ObjectDeserializer {

        @SuppressWarnings("unchecked")
        @Override
        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            String json = parser.parseObject(type);
            return (T) JSONArray.parseArray(json);
        }

        @Override
        public int getFastMatchToken() {
            return JSONToken.LITERAL_STRING;
        }
    }


    public static class ApprovalCommentSerializer implements ObjectSerializer {

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
            if (Objects.isNull(object)) {
                return;
            }
            String content = String.valueOf(object);
            if (StringUtils.isBlank(content)) {
                serializer.writeNull();
                return;
            }
            serializer.write(JSONObject.parseObject(content, ApprovalCommentListResponse.ApprovalCommentContentFileVO.class));
        }
    }

}
